package org.example.src.service.impl;

import org.example.src.dto.request.TeacherProfileRequest;
import org.example.src.dto.response.TeacherProfileResponse;
import org.example.src.entity.Teacher;
import org.example.src.entity.User;
import org.example.src.repository.TeacherRepository;
import org.example.src.repository.UserRepository;
import org.example.src.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<Teacher> findAllTeachers() {
        return teacherRepository.findAll();
    }

    @Override
    public Teacher findTeacherById(Long id) {
        return teacherRepository.findById(id).orElse(null);
    }

    @Override
    public Teacher findTeacherByTeacherId(String teacherId) {
        return teacherRepository.findByTeacherId(teacherId).orElse(null);
    }

    @Override
    public Teacher createTeacher(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    @Override
    public Teacher updateTeacher(Long id, Teacher teacherDetails) {
        Teacher teacher = teacherRepository.findById(id).orElseThrow(() -> new RuntimeException("教师未找到"));
        BeanUtils.copyProperties(teacherDetails, teacher, "id");
        return teacherRepository.save(teacher);
    }

    @Override
    public void deleteTeacher(Long id) {
        teacherRepository.deleteById(id);
    }

    @Override
    public TeacherProfileResponse updateTeacherProfile(Long id, TeacherProfileRequest request) {
        Teacher teacher = teacherRepository.findById(id).orElseThrow(() -> new RuntimeException("教师未找到"));

        teacher.setTeacherId(request.getTeacherId());
        teacher.setFullName(request.getFullName());
        teacher.setDepartment(request.getDepartment());
        teacher.setTitle(request.getTitle());
        teacher.setOfficeLocation(request.getOfficeLocation());
        teacher.setOfficeHours(request.getOfficeHours());

        Teacher updatedTeacher = teacherRepository.save(teacher);

        // 更新用户信息
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            user.setEmail(updatedTeacher.getEmail());
            userRepository.save(user);
        }

        TeacherProfileResponse response = new TeacherProfileResponse();
        BeanUtils.copyProperties(updatedTeacher, response);
        if (user != null) {
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
        }

        return response;
    }
}
